package com.project.demo.service.edu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.project.demo.dao.EduChapterMapper;
import com.project.demo.dao.EduCourseProgressMapper;
import com.project.demo.entity.edu.EduChapterEntity;
import com.project.demo.entity.edu.EduCourseProgress;
import com.project.demo.entity.param.EduCourseProgressParam;
import com.project.demo.entity.vo.R;
import com.project.demo.util.RUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 视频 service
 *
 * @author Myles Yang
 */
@Service
@Slf4j
public class EduCourseProgressService {

	@Resource
	private EduCourseProgressMapper eduCourseProgressMapper;

	@Resource
	private EduChapterMapper eduChapterMapper;



	public R getChapterVideos(EduCourseProgressParam param) {
		LambdaQueryWrapper<EduCourseProgress> queryWrapper = Wrappers.lambdaQuery(EduCourseProgress.class)
				.eq(EduCourseProgress::getCId, param.getCourseId())
				.eq(EduCourseProgress::getUId, param.getUserId());
		EduCourseProgress eduCourseProgress = eduCourseProgressMapper.selectOne(queryWrapper);
		if (eduCourseProgress != null){
			Integer count = eduChapterMapper.selectCount(Wrappers.lambdaQuery(EduChapterEntity.class)
					.eq(EduChapterEntity::getCourseId, param.getCourseId()));
			eduCourseProgress.setSumCount(count);
		}
		return RUtils.success("获取学习进度成功", eduCourseProgress);
	}

	public R saveChapterVideos(EduCourseProgressParam param) {
		//找到学习进度
		LambdaQueryWrapper<EduCourseProgress> queryWrapper = Wrappers.lambdaQuery(EduCourseProgress.class)
				.eq(EduCourseProgress::getCId, param.getCourseId())
				.eq(EduCourseProgress::getUId, param.getUserId());
		EduCourseProgress eduCourseProgress = eduCourseProgressMapper.selectOne(queryWrapper);
		if (eduCourseProgress == null){
			EduCourseProgress eduCourseProgress1 = new EduCourseProgress();
			// 插入进度
			eduCourseProgress1.setCId(param.getCourseId());
			eduCourseProgress1.setUId(param.getUserId());
			eduCourseProgress1.setProgress(1);
			eduCourseProgressMapper.insert(eduCourseProgress1);
		}else {
			//更新进度
			Integer progress = eduCourseProgress.getProgress();
			eduCourseProgress.setProgress(progress + 1);
			eduCourseProgressMapper.insert(eduCourseProgress);
		}
		return RUtils.success("保存成功");
	}
}
